package com.itgaoshu.hospitalproject.configshiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.config.ConfigurationException;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Configuration
public class ShiroConfig {
    //创建shiroFilterFactoryBean的对象
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager")DefaultSecurityManager securityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        //进行登录拦截
        Map<String,String> filterMap = new HashMap<>();
        //toLogin路径和登录页面也无需认证无需认证即可访问
        filterMap.put("/sel/toLogin","anon");
        filterMap.put("/sel/login","anon");
        filterMap.put("login.html","anon");

        //一些前端页面框架和样式也无需认证
        filterMap.put("/css/**", "anon");
        filterMap.put("/layui/**", "anon");
        filterMap.put("/js/**", "anon");
        filterMap.put("/images/**", "anon");
        filterMap.put("*.png", "anon");
        filterMap.put("*jpg", "anon");

        //其他的都需要认证才能通过
        filterMap.put("/**","authc");

        bean.setFilterChainDefinitionMap(filterMap);
        //如果访问的页面未认证，跳到登录页面
        bean.setLoginUrl("/sel/toLogin");
        return bean;
    }
    //获取SecurityManager对象
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getUserRealm")UserRealm userRealm){
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        defaultSecurityManager.setRealm(userRealm);
        return defaultSecurityManager;
    }
    //获取自定义的Realm对象
    @Bean
    public UserRealm getUserRealm(@Qualifier("getHashedCredentialsMatcher")HashedCredentialsMatcher matcher){
        UserRealm userRealm = new UserRealm();
        userRealm.setCredentialsMatcher(matcher);
        return userRealm;
    }

    //用来跟加密的密码对比的操作
    @Bean
    public HashedCredentialsMatcher getHashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(2);
        return matcher;
    }

    //shiro 与thymeleaf的整合
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }
}
